/**
 * 测试userId访问修复是否有效
 * 用于验证所有userId访问都有适当的安全检查
 */

import { getSafeUserId, isUserLoggedIn } from './user-safety.js'

/**
 * 模拟用户store状态
 */
function createMockUserStore(userInfo = null) {
  return {
    userInfo: userInfo || {
      user: null,
      approve: 0
    }
  }
}

/**
 * 测试各种用户状态下的安全性
 */
export function testUserIdAccessSafety() {
  console.log('=== 测试userId访问安全性 ===')
  
  // 测试1: 用户未登录状态
  console.log('\n1. 测试用户未登录状态:')
  const emptyStore = createMockUserStore()
  console.log('isUserLoggedIn:', isUserLoggedIn(emptyStore)) // 应该是 false
  console.log('getSafeUserId:', getSafeUserId(emptyStore)) // 应该是 null
  
  // 测试2: 用户信息不完整状态
  console.log('\n2. 测试用户信息不完整状态:')
  const incompleteStore = createMockUserStore({
    user: { userId: null },
    approve: 1
  })
  console.log('isUserLoggedIn:', isUserLoggedIn(incompleteStore)) // 应该是 false
  console.log('getSafeUserId:', getSafeUserId(incompleteStore)) // 应该是 null
  
  // 测试3: 用户信息完整状态
  console.log('\n3. 测试用户信息完整状态:')
  const completeStore = createMockUserStore({
    user: { 
      userId: '12345',
      address: '0x1234567890abcdef',
      level: 1
    },
    approve: 1
  })
  console.log('isUserLoggedIn:', isUserLoggedIn(completeStore)) // 应该是 true
  console.log('getSafeUserId:', getSafeUserId(completeStore)) // 应该是 '12345'
  
  // 测试4: 用户信息为undefined状态
  console.log('\n4. 测试用户信息为undefined状态:')
  const undefinedStore = createMockUserStore({
    user: undefined,
    approve: 1
  })
  console.log('isUserLoggedIn:', isUserLoggedIn(undefinedStore)) // 应该是 false
  console.log('getSafeUserId:', getSafeUserId(undefinedStore)) // 应该是 null
  
  console.log('\n=== 测试完成 ===')
}

/**
 * 测试修复后的函数是否安全
 */
export function testFixedFunctions() {
  console.log('=== 测试修复后的函数安全性 ===')
  
  const emptyStore = createMockUserStore()
  
  // 模拟修复后的getIncome函数
  const getIncome = async (userStore) => {
    if (userStore.userInfo.approve == 1) {
      // 添加安全检查
      if (!userStore.userInfo.user?.userId) {
        console.warn('User not logged in, skipping income fetch')
        return null
      }
      
      console.log('Fetching income for user:', userStore.userInfo.user.userId)
      return { success: true }
    }
    return null
  }
  
  // 测试未登录用户
  console.log('\n测试未登录用户调用getIncome:')
  getIncome(emptyStore).then(result => {
    console.log('Result:', result) // 应该是 null
  })
  
  // 测试已登录用户
  const loggedInStore = createMockUserStore({
    user: { userId: '12345' },
    approve: 1
  })
  
  console.log('\n测试已登录用户调用getIncome:')
  getIncome(loggedInStore).then(result => {
    console.log('Result:', result) // 应该是 { success: true }
  })
}

// 如果在浏览器环境中，将测试函数挂载到window对象
if (typeof window !== 'undefined') {
  window.testUserIdFixes = testUserIdAccessSafety
  window.testFixedFunctions = testFixedFunctions
}
